//
//  ViewController.m
//  记账本
//
//  Created by lirilu on 15/3/1.
//  Copyright (c) 2015年 glirlu@gmail.com. All rights reserved.
//

#import "ViewController.h"
#import "CNPGridMenu.h"
#import "PayMode.h"


@interface ViewController ()<CNPGridMenuDelegate>
{
    BOOL _isAdd;
}
@property(retain,nonatomic) NSMutableArray *AccountArray;
@property(retain,nonatomic) NSMutableArray *currentAccountArr;
@property(retain,nonatomic) NSMutableArray *PayModeArray;
@property(retain,nonatomic) NSMutableArray *PswArray;
@property (weak, nonatomic) IBOutlet UILabel *outLabel;
@property (weak, nonatomic) IBOutlet UIButton *timeChangeBtn;
@property (weak, nonatomic) IBOutlet UILabel *inLabel;
@property(assign,nonatomic) NSInteger timeChangeScul;

//- (IBAction)timeChangeClick:(id)sender;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UITapGestureRecognizer *singleFingerTap =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(handleSingleTap:)];
    [self.view addGestureRecognizer:singleFingerTap];
    
    _isAdd = NO;
    NSLog(@"%@",[PayMode filePath]);
}


//The event handling method
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {
//     CGPoint location = [recognizer locationInView:[recognizer.view superview]];
}

- (NSMutableArray*)AccountArray{
    if (!_AccountArray) {
        //解档
        _AccountArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[Account filePath]];
        if (!_AccountArray) {
            _AccountArray = [[NSMutableArray alloc]init];
        }
        [self InitData];

    }
    return _AccountArray;
}


- (void)InitData{
    float inMoney = 0.0f,outMoney = 0.0f,addMoney = 0.0f;
    if (_AccountArray) {
        for (Account *account in _AccountArray) {
            if (account.Money >= 0) {
                inMoney += account.Money;
            }else{
                outMoney += account.Money;
            }
            addMoney += account.Money;
        }
    }
    self.outLabel.text = [NSString stringWithFormat:@"%.2f",-outMoney];
    self.inLabel.text = [NSString stringWithFormat:@"%.2f",inMoney];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void)showPlayListView{
    _PayModeArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[PayMode filePath]];
    if (!_PayModeArray) {
        _PayModeArray = [[NSMutableArray alloc]init];
    }
    
    NSMutableArray *menuItem = [[NSMutableArray alloc] init];
    
    for (PayMode *payMode in _PayModeArray) {
        CNPGridMenuItem *item = [[CNPGridMenuItem alloc] init];
//        item.icon = [UIImage imageNamed:@"LaterToday"];
        item.title = payMode.Name;
        [menuItem addObject:item];
    }
    
    CNPGridMenu *gridMenu = [[CNPGridMenu alloc] initWithMenuItems:menuItem];
    gridMenu.delegate = self;
    [self presentGridMenu:gridMenu animated:YES completion:^{
        NSLog(@"Grid Menu Presented");
    }];

}

- (void)addRowWithMenoy:(float)menoy date:(NSString*)date{
    Account *account = [[Account alloc] init];
    account.Money = menoy;
    account.Dotime = date;
    account.PayModeStr = self.payMode.titleLabel.text;
    account.Time = (NSString*)[NSDate date];
    [self.AccountArray insertObject:(id)account atIndex:0];
    NSLog(@"%ld",[self.AccountArray count]);
    
    [self.tableView beginUpdates];
    NSMutableArray *array = [[NSMutableArray alloc]init];
    [array addObject:[NSIndexPath indexPathForItem:0 inSection:0]];
    [self.tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];
    [self.tableView endUpdates];
    //归档
    [NSKeyedArchiver archiveRootObject:self.AccountArray toFile:[Account filePath]];
    [self InitData];

}

- (NSString*) getCurrentTime{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH"];
    NSString *dateTime = [dateFormatter stringFromDate:[NSDate date]];
    return dateTime;
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"MoreBtnToMoreView"]) {
        MoreViewController *moreVC = segue.destinationViewController;
        SumStru sumStru;
        sumStru.inMoney = [self.inLabel.text floatValue];
        sumStru.outMoney = [self.outLabel.text floatValue];
        moreVC.sumStru = sumStru;
        NSLog(@"outLabel:%@,intLabel:%@,out:%f,in:%f",self.outLabel.text,self.inLabel.text,sumStru.outMoney,sumStru.inMoney);
        moreVC.archivedDelegate = self;
    }
}


#pragma mark UITabelViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.AccountArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [TableViewCell getCell:tableView Account:self.AccountArray[indexPath.row] delegate:self];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.AccountArray removeObjectAtIndex:indexPath.row];
        // Delete the row from the data source.
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [self InitData];
        
        //归档
        [NSKeyedArchiver archiveRootObject:self.AccountArray toFile:[Account filePath]];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

#pragma mark UITextFileDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == self.money) {
        [textField resignFirstResponder];
        float money = _isAdd? [textField.text floatValue]:-[textField.text floatValue];
        [self addRowWithMenoy:money date:[self getCurrentTime]];
    }else{
        [self.money resignFirstResponder];
    }
    self.money.text = @"";
    return YES;
}

#pragma mark TabelViewCellDelegate
- (void)accountChange:(Account*)accountData{
    BOOL isNeedUpdate = NO;
    for (int i = 0; i < self.AccountArray.count; i++) {
        Account *temp = self.AccountArray[i];
        if(temp.Time == accountData.Time){
            NSLog(@"temp.time:%@;accountData.time:%@",temp.Time,accountData.Time);
            self.AccountArray[i] = accountData;
//            [self.AccountArray setObject:accountData atIndexedSubscript:i];
            isNeedUpdate = YES;
            break;
        }
    }
    if (isNeedUpdate) {
        //归档
        [NSKeyedArchiver archiveRootObject:self.AccountArray toFile:[Account filePath]];
    }
}

#pragma mark - SBPickerSelectorDelegate
-(void) pickerSelector:(SBPickerSelector *)selector selectedValue:(NSString *)value index:(NSInteger)idx{
    [self.timeChangeBtn setTitle:value forState:UIControlStateNormal];
}

-(void) pickerSelector:(SBPickerSelector *)selector dateSelected:(NSDate *)date{
    
}

-(void) pickerSelector:(SBPickerSelector *)selector cancelPicker:(BOOL)cancel{
    NSLog(@"press cancel");
}

-(void) pickerSelector:(SBPickerSelector *)selector intermediatelySelectedValue:(id)value atIndex:(NSInteger)idx{
    if ([value isMemberOfClass:[NSDate class]]) {
        [self pickerSelector:selector dateSelected:value];
    }else{
        [self pickerSelector:selector selectedValue:value index:idx];
    }
}


#pragma mark CNPGridMenuDelegate
- (void)gridMenuDidTapOnBackground:(CNPGridMenu *)menu {
    [self dismissGridMenuAnimated:YES completion:^{
        NSLog(@"Grid Menu Dismissed With Background Tap");
    }];
}

- (void)gridMenu:(CNPGridMenu *)menu didTapOnItem:(CNPGridMenuItem *)item {
    [self dismissGridMenuAnimated:YES completion:^{
        NSLog(@"Grid Menu Did Tap On Item: %@", item.title);
        [self.payMode setTitle:item.title forState:UIControlStateNormal];
    }];
}

#pragma mark ArchivedDelegate
-(void)archivedName:(NSString*)name{
    [_AccountArray removeAllObjects];
    [self.tableView reloadData];
    //归档
    [NSKeyedArchiver archiveRootObject:self.AccountArray toFile:[Account filePath]];
    [self InitData];
}

#pragma mark btnClick
- (IBAction)outPayClick:(id)sender {
    [self.money setBackground:[UIImage imageNamed:@"editBoxBk_out.png"]];
    [self.money setTextColor:[UIColor redColor]];
    self.money.placeholder = @"支出金额";
    _isAdd = NO;
}

- (IBAction)payModeClick:(id)sender {
//    [self showPlayListView:YES withAnimations:YES];
    [self showPlayListView];
}

- (IBAction)inPayClick:(id)sender {
    [self.money setBackground:[UIImage imageNamed:@"editBoxBk_in.png"]];
    [self.money setTextColor:[UIColor greenColor]];
    self.money.placeholder = @"收入金额";
    _isAdd = YES;
}

//- (IBAction)timeChangeClick :(id)sender{
//    SBPickerSelector *picker = [SBPickerSelector picker];
//    
//    picker.pickerData = [@[@"全部",@"这星期",@"这个月",@"三个月"] mutableCopy]; //picker content
//    picker.delegate = self;
//    picker.pickerType = SBPickerSelectorTypeText;
//    picker.doneButtonTitle = @"确定";
//    picker.cancelButtonTitle = @"取消";
//    
//    //    picker.pickerType = SBPickerSelectorTypeDate; //select date(needs implements delegate method with date)
//    //    picker.onlyDayPicker = YES;  //if i want select only year, month and day, without hour (default NO)
//    //    picker.datePickerType = SBPickerSelectorDateTypeOnlyHour;
//    
//    //    [picker showPickerOver:self];
//    
//    CGPoint point = [self.view convertPoint:[sender frame].origin fromView:[sender superview]];
//    CGRect frame = [sender frame];
//    frame.origin = point;
//    [picker showPickerIpadFromRect:frame inView:self.view];
//    
//
//}
@end
